import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    opened: true,
    userInfo: sessionStorage.getItem("userInfo")
      ? // JSON字符串转换成对象 并查看sessionStorage是否有该值
        JSON.parse(sessionStorage.getItem("userInfo"))
      : null,
    cms_token: sessionStorage.getItem("cms_token")
      ? sessionStorage.getItem("cms_token")
      : null,
  },
  getters: {
    // 类似store的计算属性
    token(state) {
      return state.cms_token;
    },
  },
  //  mutation 必须是同步函数
  mutations: {
    SET_OPENED(state) {
      state.opened = !state.opened;
    },
    SET_USERINFO(state, userInfo) {
      // 提取用户信息
      state.userInfo = userInfo;
      // 提取用户token
      state.cms_token = userInfo.token;

      // sessionStorage 将value储存到 cms_token 或 userInfo字段
      sessionStorage.setItem("cms_token", state.cms_token);
      // JSON.stringify 将js值 转换成JSON
      sessionStorage.setItem("userInfo", JSON.stringify(userInfo));
    },
  },
  actions: {},
  modules: {},
});
